<?php

namespace App\Models;

use App\Models\Traits\Timestamp;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    use HasFactory,Timestamp;

    public static $model_status = [
        0   => '未付款',
        1   => '待确认',
        2   => '已确认',
    ];

    protected $fillable = [
        'order_no','sale_user_id','buy_user_id','auction_id','product_id','amount','integral','voucher','status'
    ];

    public function sale_user()
    {
        return $this->belongsTo(AppUser::class,'sale_user_id');
    }

    public function buy_user()
    {
        return $this->belongsTo(AppUser::class,'buy_user_id');
    }

    public function product()
    {
        return $this->belongsTo(Product::class,'product_id');
    }

    protected $primaryKey = 'order_no';

    public $incrementing = false;

    protected static function booted()
    {
        static::updated(function ($model){

            if ($model->isDirty('status') && $model->status == 2){

                $product = Product::find($model->product_id);

                $product->user_id = $model->buy_user_id;
                $product->transfer = 0;
                $product->save();
            }

        });
    }
}
